<template>
  <div>
     <el-form ref="form" :model="form" :rules="rules">
      <el-form-item label="位置" label-width="120px" prop="ad_which_page">
        <el-select v-model="form.ad_which_page" placeholder="请选择位置">
            <el-option v-for="item in positionList" :key="item.ad_which_page" :label="item.ad_which_page_title" :value="item.ad_which_page"></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="名称" label-width="120px" prop="ad_title">
        <el-input class="myinput" placeholder="请输入" v-model="form.ad_title" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="图片" label-width="120px" prop="ad_img_url">
        <div class="imgcon">
          <img class="preimg ml10" v-if="form.ad_img_url" :src="imgUrl+form.ad_img_url" alt="">
          <div class="file-con ml10">
            <el-button type="success">上传图片</el-button>
            <input type="file" ref="file" class="file" @change="upImg">
          </div>
          <div class="tip">
            尺寸：建议 750 * 324
          </div>
        </div>
      </el-form-item>
      <el-form-item label="跳转页面" label-width="120px" >
        <el-radio-group v-model="form.ad_type">
          <el-radio  :label="2">内部页面</el-radio>
          <el-radio  :label="1">外部页面</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="地址" label-width="120px" prop="mobilenum">
        <!-- TODO 引入内部地址 -->
        <div v-if="form.ad_type==2">
          <el-input class="myinput ml10"  placeholder="请选择" key="1" :disabled="true" v-model="form.info_id" autocomplete="off"></el-input>
          <el-dropdown @command="handleCommand">
            <el-button type="text">设置地址<i class="el-icon-arrow-down el-icon--right"></i></el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="ser">系列</el-dropdown-item>
              <el-dropdown-item command="comd">商品</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          
        </div>
        

        <el-input class="myinput ml10" v-if="form.ad_type==1" placeholder="请输入链接地址" key="2" v-model="form.ad_url" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="状态" label-width="120px" >
        <el-radio-group v-model="form.ad_status">
          <el-radio  :label="1">上线</el-radio>
          <el-radio  :label="2">下线</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label-width="120px" >
        <el-button @click="goback">取消</el-button>
        <el-button type="primary" @click="saveAd">保存</el-button>
      </el-form-item>
    </el-form>
    <!-- 图片裁切 -->
    <el-dialog title="图片裁切" width="800px" :visible.sync="dialogVisible2">
      <div>
        <div class="imgwrap">
          <div class="left">
            <div class="avatar-wrapper">
              <img ref="cimg" :src="imgSrc" alt="">
            </div>
          </div>
          <div class="right" >
            <div>
              <div ref="preimg" class="avatar-preview" ></div>
              <div>宽度：{{imgWidth}}</div>
              <div>高度：{{imgHeight}}</div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer">
        <el-button @click="dialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="cropImage" :loading="isup">确 定</el-button>
      </span>
    </el-dialog>
    <!-- // 设置链接 -->
    <el-dialog title="设置链接" width="800px" :visible.sync="dialogVisible">
      <div>
        <div>
          <el-form size="small" :inline="true" :model="queryObj" v-if="setType=='comd'" >
            <el-form-item label="系列">
              <el-select v-model="queryObj.series_id" placeholder="全部">
                <el-option v-for="item in seriesList" :key="item.series_id" :label="item.series_name" :value="item.series_id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="关键字">
              <el-input
                placeholder="请输入"
                clearable
                prefix-icon="el-icon-search"
                v-model="queryObj.query_value">
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="_getMainList">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div>
          <el-table
            :data="mainList"
            stripe
            class="small-table"
            style="width: 100%">
            <el-table-column
              prop="info_id"
              :label="tabobj.id"
              width="100">
            </el-table-column>
            <el-table-column
              prop="info_content"
              :label="tabobj.content"
            >
            </el-table-column>
            <el-table-column
              label="操作"
              width="150">
              <template slot-scope="scope">
                <el-button type="text" @click="setUrlLink(scope.row)">添加</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            class="pagecon"
            background
            layout="prev, pager, next"
            :current-page.sync="page.page"
            @current-change="_getMainList"
            :total="page.total">
          </el-pagination>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import {getQiniuToken} from 'api/commonApi'
import config from 'api/config'
import * as qiniu from 'qiniu-js'
import {getPositionList, addOrEditAd} from 'api/ADmanagementAPI'
import { getSeriesAll } from 'api/lineManagement/seriesMgAPI';
import { getCommodityList } from 'api/lineManagement/lineCommodity'
import {mapState} from 'vuex'
export default {
  computed: {
    ...mapState('admoduleData', ['AdData']),
    tabobj() {
      if(this.setType == 'ser') {
        return {
          id: 'ID',
          content: '系列名称'
        }
      }else{
        return {
          id: '产品id',
          content: '线路名称'
        }
      }
    }

  },
  data() {
    return {
      setType: 'ser',
      imgUrl: config.imgUrl,
      isup: false,
      form: {
        ad_status: 1,
        ad_type: 2
      },
      queryObj: {},
      mainList: [],
      options: [],
      imgWidth: '',
      imgHeight: '',
      props: {
        value: 'category_id',
        label: 'category_name',
        children: 'child'
      },
      seriesList: [],
      page: {
          page: 1,
          limit: 10,
          total: 0
      },
      positionList: [],
      rules: {
        ad_title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        ad_img_url: [
          { required: true, message: '请上传图片', trigger: 'change' }
        ]
      },
      imgSrc: '',
      dialogVisible2: false,
      dialogVisible: false
    }
  },
  methods: {
    goback() {
      this.$router.back()
    },
    // 初始化裁切矿
    initCrop() {
      console.log(123, this.$refs.cimg)
      this.cropper = new Cropper(this.$refs.cimg, {
        guides: true,
        viewMode: 0,
        autoCropArea: 1,
        dragMode: "crop",
        background: "true",
        preview: this.$refs.preimg,
        crop: (event) => {
          this.imgWidth = event.detail.width | 0
          this.imgHeight = event.detail.height | 0
        },
      })
    },
    cropImage() {
      this.cropper.getCroppedCanvas().toBlob((blob) => {
        this._upimg(blob)
      })
    },
    handleCommand(type) {
      this.setType = type
      this.dialogVisible = true
      this.page = {
        page: 1,
        total: 0
      }
      this._getMainList()
    },
    // 添加广告
    saveAd() {
      this.$refs['form'].validate().then(() => {
        let sendData = JSON.parse(JSON.stringify(this.form))
        if(sendData.ad_type === 2) {
          sendData.ad_url = ''
        }else if(sendData.ad_type === 1) {
          sendData.info_id = 0
        }
        addOrEditAd(sendData).then(res => {
          if(res) {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.$router.push('/home/carouselManagement')
          }
        })
      })
    },
    // 上传到服务器
    async _upimg(file) {
      let res = await getQiniuToken()
      let token = res.rData[0].token
      // let putExtra ={
      //   fname: "",
      //   params: {},
      //   mimeType: null
      // }
      // let config = {
      //   useCdnDomain: true,
      //   region: null
      // }
      var observable = qiniu.upload(file, null, token, null, null);
      // qiniu.upload(file, this.fileName, token, putExtra, config)

      observable.subscribe({
        next: (res) =>{
          this.isup = true
          console.log('进度', res)
        },
        error: (err) => {
          this.isup = false
          this.$message({
            message: err.message,
            type: 'error'
          })
          console.log('错误', err)
        }, 
        complete: (res) => {
          this.isup = false
          this.dialogVisible2 = false
          this.form.ad_img_url = res.key
          this.$message({
            message: '上传成功',
            type: 'success'
          })
          console.log('完成', res)
        }
      })
    },
    upImg(event){
      var files = event.target.files
      this.$nextTick(()=>{
        event.target.value = null
      })
      files = Array.from(files)
      files.forEach((file) => {
          if(file.size>5*1024*1024){
            alert('上传文件只能为5M内')
          }else{
            // 读取到文件
            this.dialogVisible2 = true
            this.fileName = file.name
            if (this.imgSrc) {
              URL.revokeObjectURL(this.imgSrc) // Revoke the old one
            }
            this.imgSrc = URL.createObjectURL(file)
            // this.startCropper()
            this.$nextTick(()=>{
              if(!this.cropper){
                this.initCrop()
              }else{
                this.cropper.replace(this.imgSrc)
              }
            })
          }
      })
    },
    setUrlLink(row){
      console.log(row)
      this.form.info_id = row.info_id
      this.dialogVisible = false
    },
    // 获取全部系列
    // huo qu 系列
    async _getSeriesAll() {
      let res = await getSeriesAll()
      this.seriesList = res.rData
    },
    // 获取商品
    _getCommodityList() {
      let data = { ...this.queryObj };
      data.pageInfo = { ...this.page };
      getCommodityList(data).then(res => {
        let pageInfo = res.pageInfo;
        this.page.total = pageInfo.Total;
        this.page.page = pageInfo.page;
        this.mainList = res.rData.map(item =>({info_id: item.commodity_id, info_content: item.commodity_name}))
      });
    },
    async _getMainList() {
      if(!this.seriesList.length) {
        await this._getSeriesAll()
        console.log(1)
      }
      if(this.setType=='ser') {
        this.page.total = this.seriesList.length;
        console.log(2)
        let start = (this.page.page-1)*10
        console.log(this.seriesList, start)
        let newarr = this.seriesList.slice(start, start+9)
        
        this.mainList = newarr.map(item =>({info_id: item.series_id, info_content: item.series_name}))
      }else{
        this._getCommodityList()
      }
    },
    _getPositionList() {
      getPositionList().then(res => {
        this.positionList = res.rData
        if(!this.AdData.ad_id){
          this.form.ad_which_page = this.positionList[0].ad_which_page
        }
      })
    }
  },
  mounted() {
    // 判断是否为编辑
    if(this.$route.params.id && !this.AdData.ad_id) {
      this.$router.replace('/home/carouselManagement')
      return 
    }
    this.form = JSON.parse(JSON.stringify(this.AdData))
    // 初始化
    this._getPositionList()
    // this._getContentList()
    // this._getCateGoryAllList()
  }
}
</script>

<style lang="scss" scoped>
.imgwrap{
  display: flex;
  .left{
    width: 500px;
    height: 300px;
  }
  .right{
    flex: 1;
  }
}
img {
  max-width: 100%; /* This rule is very important, please do not ignore this! */
}
.avatar-wrapper{
  width: 450px;
  height: 195px;
}
.preimg{
  width: 225px;
  height: 98px;
}
.avatar-preview{
  width: 225px;
  height: 98px;
  background: #f5f5f5;
  margin-bottom: 10px;
  overflow: hidden;
}
.myinput{
  width: 250px;
  display: inline-block;
}
.ml10{
  margin-right: 10px;
}
.imgcon{
  display: flex;
  align-items: flex-end;
  .file-con{
    position: relative;
    .file{
      position: absolute;
      height: 100%;
      width: 100%;
      top: 0;
      left: 0;
      opacity: 0;
    }
  }
  .tip{
    margin-top: 10px;
    color: #666;
  }
}
</style>
